const Router = require('koa-router');
const {db, Op,QueryTypes } = require("../../models/db");
const {xe} = require("../../tools/tool");
const router = new Router();

// 查询商品库存
router.post('/zd/getGoodList', async ctx => {
     let usr = ctx.user
    let tenantId = usr.tenantId;
    let catId = ctx.request.body.catId;
    let name = ctx.request.body.name?xe.trim(ctx.request.body.name):'';
    let currentPage = ctx.request.body.currentPage?ctx.request.body.currentPage:1;
    let pageSize = 20;
    let skip = (currentPage - 1) * pageSize;
    let sql = `select tenantId,id,name,unit1 unit,unit1,isnull(unit2,'') unit2,spec,isnull(price2,0) price2,imgUrl from v_goods where tenantId=${tenantId}  `
    if(name) {
        sql += ` and (name like '%${name}%' or pinYin like '%${name}%') `
    }
    // 最近
    if(catId === -1) {
        let ids = []
        let lists = await db.query(`select top 500 b.invId from invoice a inner join v_main_info b on a.tenantId=b.tenantId and a.id=b.iid and a.tenantId=${tenantId} and a.buId=${usr.buId} order by b.id desc `,{
            type: QueryTypes.SELECT
        })
        lists.map(row => {
            if(ids.indexOf(row.invId) === -1) {
                ids.push(row.invId)
            }
        })
        if(ids.length > 0) {
            sql += ` and id in(${ids.join(',')}) `
        }
        if(ids.length === 0) return ctx.suc('', {list: []})
    }
    else if (catId === 0) {
        // 全部
    }
    else {
        if(catId) {
            let mod = await db.models['goodsCat'].findOne({
                where:{
                    tenantId,
                    id: catId
                }
            })
            if(mod && mod.code) {
                sql += ` and goodCatCode like '${mod.code}%' `
            }
        }
    }
    let res = `select a.id,a.name,a.spec,a.unit,a.unit1,a.unit2,a.imgUrl,iif(b.price is null,isnull(a.price2,0),b.price) price,isnull(b.deduction,0) deduction,
                      c.sendInvId,c.buyQty,c.sendQty 
            from (${sql}) a
             left join (select tenantId,invId,price,unit,deduction from v_price_his_last where tenantId=${tenantId} and buId=${usr.buId}) b on a.tenantId=b.tenantId and a.id=b.invId and a.unit1=b.unit
              left join (select tenantId,buId,invId,sendQty,buyQty,sendInvId from v_send_last where tenantId=${tenantId} and buId=${usr.buId}) c on a.tenantId=c.tenantId and a.id=c.invId
`
    res += ` order by name offset ${skip} rows fetch next ${pageSize} rows only;`
    let list = await db.query(res, {type: QueryTypes.SELECT})
    list.map(row => {
        row.send = ''
        row.deduction = xe.toNumber(row.deduction) === 0 ? '' : xe.toFixed(row.deduction)
        if(row.buyQty) {
            row.send = `买${row.buyQty}赠${row.sendQty}`
        }
    })

    return ctx.suc('', {
        list
    })
})

module.exports = router;
